﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using ChBusiness.User;
using ChBusiness;

using ChBusiness.Common;
using ChBusiness.Struct;
using System.Text;
using ChBusiness.Wsbs;
using Common;

public partial class Wsbs_SelectSerialOperation : System.Web.UI.Page
{
    UserRightRequest rightRequest = new UserRightRequest();
    private UploadFileClass uploadFileClass = new UploadFileClass();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindData();
            BindFlowName();
            Session["DangQianRenWu"] = "事项办理权限申请";
        }

        DeleteResource();
    }

    /// <summary>
    /// 删除附件
    /// </summary>
    private void DeleteResource()
    {
        if (!string.IsNullOrEmpty(Request["id"]) && Request["action"].CompareTo("delete") == 0)
        {
            rightRequest.DeleteRightInfo(Request["id"]);
            string strSql = string.Format(@"delete from sys_user_serial where id = '{0}'", Request["id"]);
            //添加操作日志 addby zhongjian 20100421
            string strRemark = string.Format("删除业务权限的申请");
            SystemLogs.AddSystemLogs(Session["UserId"].ToString(), "delete", strRemark, strSql);

            BindData();
        }
    }

    /// <summary>
    /// 绑定流程名称(除涉密业务)
    /// </summary>
    /// <!--addby zhongjian 201003158-->
    public void BindFlowName()
    {
        WebWork cWorks = new WebWork();
        DataTable dtTable = cWorks.GetWorkFlow();
        ddlFlow.Items.Clear();
        foreach (DataRow row in dtTable.Rows)
        {
            ddlFlow.Items.Add(new ListItem(row["flowtype"].ToString(), row["flowname"].ToString()));
        }
    }

    /// <summary>
    /// 绑定数据源,绑定datagrid
    /// </summary>
    private void BindData()
    {
        if (Session["UserId"] != null)
        {
            DataTable dtSource = rightRequest.GetAllRightByUser(Session["UserId"].ToString());
            CustomGridView1.DataSource = dtSource;
            CustomGridView1.PageSize = SystemConfig.PageSize;
            CustomGridView1.RecordCount = dtSource.Rows.Count;
            CustomGridView1.DataBind();
        }
    }

    /// <summary>
    /// 保存申请流程权限上传附件方法
    /// </summary>
    /// <param name="strSerialID">流程权限ID</param>
    /// <!--addby zhongjian 20091111-->
    private void SaveSerialAtt(string strSerialID)
    {
        FileUploadStruct _fileUploadStruct = new FileUploadStruct();
        _fileUploadStruct.TableName = "sys_user_serialatt";
        _fileUploadStruct.KeyId = "id";
        _fileUploadStruct.FileStoreFieldName = "filedata";
        _fileUploadStruct.FileTypeFieldName = "filetype";
        _fileUploadStruct.StoreResourceFieldName = "filename";
        _fileUploadStruct.StoreParamFieldName = "serial_id";
         //验证文件类型
        String strFileExtension = System.IO.Path.GetExtension(file1.FileName);
        string strFileName=file1.FileName.Replace(strFileExtension, "");
        strFileExtension = strFileExtension.ToLower();
        if (strFileExtension != null && strFileExtension != "")
        {
            //开始上传  
            
            _fileUploadStruct.FileBytes = file1.FileBytes;//文件数据
            _fileUploadStruct.FileTypeFieldValue = strFileExtension;//文件类型
            _fileUploadStruct.StoreResourceNameValue = strFileName; //文件名称
            _fileUploadStruct.StoreParamValue = strSerialID;//流程权限ID
            DataStoreType storeType = DataStoreType.Insert;
            int nResult=rightRequest.StoreSerialAtt(_fileUploadStruct, storeType);
        }
        else
        {
            WindowAppear.WriteAlert(this.Page, "对不起，系统不支持您选择上传的文件类型！");
        }

    }

    /// <summary>
    /// 保存申请流程权限上传附件方法(批量上传附件)
    /// </summary>
    /// <param name="strSerialID">流程权限ID</param>
    /// <!--addby zhongjian 20091112-->
    private void SaveFileAtt(string strSerialID)
    {
        //遍历File表单元素
        HttpFileCollection files = HttpContext.Current.Request.Files;
        //状态信息
        StringBuilder strMsg = new StringBuilder();
        try
        {
            //设置附件存储的属性
            FileUploadStruct _fileUploadStruct = new FileUploadStruct();
            _fileUploadStruct.TableName = "sys_user_serialatt";
            _fileUploadStruct.KeyId = "id";
            _fileUploadStruct.FileStoreFieldName = "filedata";
            _fileUploadStruct.FileTypeFieldName = "filetype";
            _fileUploadStruct.StoreResourceFieldName = "filename";
            _fileUploadStruct.StoreParamFieldName = "serial_id";

            byte[] filebyte;//文件数据
            string fileName = string.Empty;//文件名称
            string fileExtension = string.Empty;//文件类型

            for (int iFile = 0; iFile < files.Count; iFile++)
            {
                //检查文件扩展名字
                HttpPostedFile postedFile = files[iFile];
                fileName = System.IO.Path.GetFileName(postedFile.FileName);
                if (fileName != "")
                {
                    filebyte = new byte[postedFile.ContentLength];
                    postedFile.InputStream.Read(filebyte, 0,postedFile.ContentLength);   

                    fileExtension = System.IO.Path.GetExtension(fileName);
                    if (fileExtension != null && fileExtension != "")
                    {
                        fileName=fileName.Replace(fileExtension, ""); //文件名称
                        //验证文件类型
                        fileExtension = fileExtension.Replace(".", "");
                        fileExtension = fileExtension.ToLower();
                        bool bOk = uploadFileClass.HaveValideFileExtension(fileExtension);
                        if (bOk)
                        {
                            //开始上传 
                            _fileUploadStruct.FileBytes = filebyte;//文件数据
                            _fileUploadStruct.FileTypeFieldValue = fileExtension;//文件类型
                            _fileUploadStruct.StoreResourceNameValue = fileName; //文件名称
                            _fileUploadStruct.StoreParamValue = strSerialID;//流程权限ID
                            DataStoreType storeType = DataStoreType.Insert;
                            int nResult = rightRequest.StoreSerialAtt(_fileUploadStruct, storeType);

                            //添加操作日志 addby zhongjian 20100421
                            string strRemark = string.Format("申请 {0} 业务权限，ID为 {1} 时，上传附件资料： {2}.{3}", ddlFlow.Text, strSerialID, fileName, fileExtension);
                            SystemLogs.AddSystemLogs(Session["UserId"].ToString(), "add", strRemark, "");
                        }
                        else
                        {
                            int num = iFile + 1;
                            strMsg.Append("对不起，系统不支持第 [" + num + "] 个文件类型！");
                            strMsg.Append("上传文件名：" + fileName + "");
                            WindowAppear.WriteAlert(this.Page, strMsg.ToString());
                        }
                    }
                }                               
            }
        }
        catch (System.Exception Ex)
        {
            strMsg.Append("上传附件时发生错误：");
            strMsg.Append(Ex.Message);
            WindowAppear.WriteAlert(this.Page, strMsg.ToString()); 
        }
    }


    /// <summary>
    /// 绑定数据
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void CustomGridView1_OnLoadData(object sender, EventArgs e)
    {
        BindData();
    }

    /// <summary>
    /// 行创建
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void CustomGridView1_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            HyperLink hlTemp = e.Row.FindControl("hlDelete") as HyperLink;

            if (hlTemp != null)
            {
                DataRowView dtr = (DataRowView)e.Row.DataItem;

                if (dtr != null)
                {
                    hlTemp.Attributes.Add("onclick", "return confirm('您确定要删除吗？')");//为删除添加提示
                    hlTemp.NavigateUrl = string.Format("SelectSerialOperation.aspx?id={0}&action=delete",
                        dtr["id"]);
                }
            }
        }
    }

    /// <summary>
    /// 保存
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (Session["UserId"] != null)
        {
            if (txtNotes.Text.Trim() == "")
            {
                WindowAppear.WriteAlert(this.Page, "请认真填写申请理由！");
                return;
            }
            if (txtNotes.Text.Trim().Length > 3000)
            {
                WindowAppear.WriteAlert(this.Page, "输入的内容过多！");
                return;
            }

            string nReturn = rightRequest.SaveRightInfo(Session["UserId"].ToString(), ddlFlow.SelectedValue, ddlFlow.SelectedItem.Text, txtNotes.Text);
            if (nReturn != "")
            {
                SaveFileAtt(nReturn);//上传附件
                WindowAppear.WriteAlert(this.Page, "提交成功");
                //this.Response.Write("<script>ymPrompt.succeedInfo({message:document.getElementById('txt').innerHTML,width:400,height:260,handler:handler2});</script>");
                BindData();
            }
        }
    }

    /// <summary>
    /// 设置删除权限(已通过审批的流程无权限删除)
    /// </summary>
    /// <param name="IDataItemContainer"></param>
    /// <returns></returns>
    /// <!--addby zhongjian 20091104-->
    public bool SetDelete(IDataItemContainer row)
    {
        bool flag = true;
        string strDelete = "";//删除权限值
        if (DataBinder.Eval(row.DataItem, "is_pass") != DBNull.Value)
        {
            strDelete = DataBinder.Eval(row.DataItem, "is_pass").ToString();
            if (strDelete == "1")
                flag = false;
        }        
        return flag;
    }

    /// <summary>
    /// 获取是否通过值
    /// </summary>
    /// <param name="row"></param>
    /// <returns></returns>
    /// <!--addby zhongjian 20091110-->
    public string BindPub(IDataItemContainer row)
    {
        string strReturn = "未通过";
        if (DataBinder.Eval(row.DataItem, "is_pass") != DBNull.Value)
        {
            strReturn = DataBinder.Eval(row.DataItem, "is_pass").ToString();
            if (strReturn == "1")
                strReturn = "已通过";
            else
                strReturn = "未通过";
        }
        return strReturn;
    }

}
